import React from "react";
import ReactDOM from "react-dom/client";
import { createHashRouter } from "react-router";
import Home from "../pages/Home";
import About from "../pages/About";
import Layout from "../layout"; 
import NotFound from "../layout/404";
import Error from '../layout/error';

const data = [
    {name:"张三",age:18},
    {name:"李四",age:20},
    {name:"王五",age:22},
]

const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); 

const router = createHashRouter([
    // {
    //     path: "/",
    //     Component: Home
    // },
    // {
    //     path: "/about",
    //     Component: About
    // }
    {
        path: "/", // 父路由 可省略
        Component: Layout,
        children: [
            // 子路由不需要加/前缀
            {
                path: "home",
                // index: true, // 默认子路由
                Component: Home,
                loader: async () => {
                    await sleep(2000)
                    // 模拟fetch 获取数据
                    return{
                        data,
                        success:true
                    }
                },
                // 提交后会默认执行一次loader
                action: async ({ request }) => { 
                // const formData = await request.formData() // 默认就是通过fromdata接收数据
                // const json = Object.fromEntries(formData)
                const json = await request.json() 
                console.log(json)
                await sleep(2000) // 模拟接口异步操作
                return {
                    success: true,
                    message: "提交成功"
                }
            },
            },
            
            // {
            //     path: "about/:id/:name", // 动态路由 params传参 不可以传递对象
            //     Component: About
            // }
            {
                path: "about",
                lazy: async () => {
                    // 模拟两秒钟的延迟
                    await sleep(2000);
                    const about  = await import("../pages/About"); // 这种方式默认会代码分包，减少主包大小
                    console.log("ABOUT=", about);
                    return {
                        Component: about.default
                    }
                },
                loader: async () => {
                    // throw new Response('Not Found', {status: 404});
                    throw {
                        message: 'Not Found',
                        status: 404,
                        statusText: 'Not Found',
                        data: '132131',
                    }
                },
                ErrorBoundary: Error, // 只有loader或者action报错才会触发
            }
        ]
    },
    {
        path: "*",
        Component: NotFound,
    }
])


export default router;